package com.word;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class word2swfController extends Controller{
	
	private File sourceFile;
	private File pdfFile;
	private File swfFile;
	private Runtime r;
	
	
	@ActionKey("/word2swf")
	public void word2swf() throws IOException
	{
		String s=getClass().getResource("/").getFile().toString();
		s=s.substring(0, s.lastIndexOf("/WEB-INF"));
		s=URLDecoder.decode(s,"utf-8");
		
		//上面几行可以实现路径中存在空格时不将空格转换为%20
		
		String URL=getPara("URL");
		System.out.println(URL);
		URL=URL.substring(0, URL.lastIndexOf(".doc"));
		sourceFile =new File(s+"/WEB-INF/uploadDir/student/04/2011/kickoff_report/"+URL+".doc");
		pdfFile =new File(s+"/doc/"+URL+".pdf");
		swfFile =new File(s+"/doc/temp.swf");
		System.out.println(sourceFile);
		System.out.println(pdfFile);
		
		System.out.println(sourceFile.getAbsolutePath());
		
		if(sourceFile.exists())
		{
			if(!pdfFile.exists())
			{
				OpenOfficeConnection connection =new SocketOpenOfficeConnection(8100);
				connection.connect();
				DocumentConverter converter=new OpenOfficeDocumentConverter(connection);
				converter.convert(sourceFile, pdfFile);
				pdfFile.createNewFile();
				connection.disconnect();
				System.out.println("转换为pdf格式 路径"+pdfFile.getParent());
			}
			else 
			{
				System.out.println("已转换到pdf");
			}
		}
		else
		{
			System.out.println("转换文件不存在");
		}
		r=Runtime.getRuntime();
		if(!swfFile.exists())
		{
			if(pdfFile.exists())
			{
				try {
					Process p=r.exec("C:/Program Files (x86)/SWFTools/pdf2swf.exe \""+pdfFile.getPath()+
						"\" -o \""+swfFile.getPath()+"\" -T 9");
					p.waitFor();
					swfFile.createNewFile();
					System.out.println("3转换为swf 路径"+swfFile.getPath());
					System.out.println("4转换为swf 名称"+swfFile.getName());
					if(pdfFile.exists())
					{
						pdfFile.delete();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else
			{
				System.out.println("pdf不存在");
			}
		}
		else
		{
			System.out.println("已转化为swf无需转换");
		}
		renderJson("{\"success\":true}");
	}
}
